<template>

    <!-- 未曾登录钱包的界面 -->
    <div class="wallet-container" v-if="isLogin == false">

        <div class="wallet-header-menu" v-if="isShowMenu">
            <div class="wallet-header-menu-container">
                <div class="block_li">
                    <span class="arrow-down">{{ $setI18n('lang_selectLang','选择语言') }}</span>
                    <div class="picker-block">
                        <div class="li" @click="handleClickChangeLang(0)"><i></i>{{ $setI18n('lang_chinese','中文') }}</div>
                        <div class="li" @click="handleClickChangeLang(1)"><i></i>English</div>
                        <div class="li" @click="handleClickChangeLang(2)"><i></i>Indonesia</div>
                        <div class="li" @click="handleClickChangeLang(3)"><i></i>Philippines</div>
                        <div class="li" @click="handleClickChangeLang(4)"><i></i>Russia</div>
                    </div>
                </div>
                <div class="block_li">
                    <span class="arrow-down">Testnet</span>
                    <div class="picker-block">
                        <div class="li"><i></i>{{ $setI18n('lang_alphaVersion','Alpha版本') }}</div>
                    </div>
                </div>
            </div>
            <div class="wallet-header-menu-mesk" @click="isShowMenu = false"></div>
        </div>

        <div class="wallet-header">

            <a href="/" class="logo">
                <img :src="getLogoImage" alt="" />
            </a>

            <div class="wallet-more-btn" @click="isShowMenu = true"></div>

            <div class="language-picker">
                <span class="arrow-down">{{ $setI18n('lang_selectLang','选择语言') }}</span>
                <div class="picker-block">
                    <div class="li" @click="handleClickChangeLang(0)">{{ $setI18n('lang_chinese','中文') }}</div>
                    <div class="li" @click="handleClickChangeLang(1)">English</div>
                    <div class="li" @click="handleClickChangeLang(2)">Indonesia</div>
                    <div class="li" @click="handleClickChangeLang(3)">Philippines</div>
                    <div class="li" @click="handleClickChangeLang(4)">Russia</div>
                </div>
            </div>

            <div class="language-picker language-picker-2">
                <span class="arrow-down">Testnet</span>
                <div class="picker-block">
                    <div class="li">{{ $setI18n('lang_alphaVersion','Alpha版本') }}</div>
                </div>
            </div>

        </div>
        <div class="wallet-body">
            <h1 class="welcome-title">{{ $setI18n('lang_welcome2','欢迎登陆Smartx钱包') }}</h1>
            <div class="wallet-funcs2">
                <div class="funcs-item  funcs-item-bg1" @click="handleClickLoadWallet">
                    <span class="funcs-title">{{ $setI18n('lang_comeinWallet','进入钱包') }}</span>
                    <p>{{ $setI18n('lang_comeinWallet_tips_1','如果已有钱包，请进入钱包') }}</p>
                </div>
                <!--<div class="funcs-item  funcs-item-bg2" @click="handleClickCreateWallet">
                    <span class="funcs-title">{{ $setI18n('lang_createWallet','创建新钱包') }}</span>
                    <p>{{ $setI18n('lang_comeinWallet_tips_2','如果没钱包，请创建新钱包') }}</p>
                </div>-->
            </div>
        </div>


        <!-- 创建钱包输入密码界面 -->
        <div class="popUp-window"
             v-if="isCreateWallet == true && isLoadWallet == false"
             :style="isCreateWallet == true && isLoadWallet == false && isShowDownLoadJson == false ? 'display:block':''">

            <div class="window-wrapper pwd-container popUp-window-pwd">
                <div class="window-content">
                    <p class="pwd-title">{{ $setI18n('lang_comeinWallet_password','密码') }}</p>
                    <div class="input-area">
                        <input type="password" :placeholder="$setI18n('lang_comeinWallet_password_placeholder','请输入密码')" v-model.trim="pwd">
                        <div class="process-bar" :style="{'left': pwdStyle()}"></div>
                    </div>

                    <div class="pwd-level">{{ $setI18n('lang_comeinWallet_power','密码强度') }}：<span class="blue-font">{{ pwdDifficultyText }}</span></div>

                    <div class="input-area">
                        <input type="password" :placeholder="$setI18n('lang_comeinWallet_password_placeholder_again','请再输入密码')" v-model.trim="pwd2">
                    </div>

                    <div class="common-btn enter-wallet" @click="handleClickCreateWalletForWindow">{{ $setI18n('lang_comeinWallet_text','创建钱包') }}</div>

                </div>
            </div>
            <div class="popUp-window-mesk" @click="handleClickCloseWindow"></div>
        </div>


        <!-- 登录钱包输入密码界面 -->
        <div class="popUp-window" v-if="isInputPwdWallet == true" :style="isInputPwdWallet == true ? 'display:block':''">

            <div class="window-wrapper pwd-container">
                <div class="window-content">
                    <p class="pwd-title">{{ $setI18n('lang_comeinWallet_password','密码') }}</p>
                    <div class="input-area">
                        <input type="password" :placeholder="$setI18n('lang_comeinWallet_password_placeholder','请输入密码')" v-model.trim="pwd3" />
                    </div>

                    <div class="common-btn enter-wallet" @click="loadWalletFromFile">{{ $setI18n('lang_comeinWallet','进入钱包') }}</div>

                </div>
            </div>

            <div class="popUp-window-mesk" @click="handleClickCloseWindow"></div>
        </div>


        <!-- 上传keystore文件 -->
        <div class="popUp-window" :style="isShowUpLoadWallet == true ? 'display:block !important':''">

            <div class="window-wrapper upload-keystore-file">
                <div class="window-content">
                    <div class="circle-box">
                        <img :src="getBlackLogoPng" alt="" />
                    </div>
                    <p class="upload-tips">{{ $setI18n('lang_comeinWallet_pleaseUpload','请上传keystore文件') }}</p>
                    <div class="common-btn continue-btn">
                        <input type="file" class="inputFile" @change="addFileJson" ref="inputFile" id="load" />
                        {{ $setI18n('lang_comeinWallet_selectKs','选择keystore文件') }}
                    </div>
                    <div class="warning">{{ $setI18n('lang_comeinWallet_tips_2','如果没钱包，请创建新钱包') }}</div>
                </div>
            </div>
            <div class="popUp-window-mesk" @click="handleClickCloseWindow"></div>
        </div>

        <!-- 成功创建钱包 -->
        <div class="popUp-window" v-if="isShowSuccessCreateWallet == true" :style="isShowSuccessCreateWallet == true ? 'display:block':''">
            <div class="window-wrapper success-deal create-wallet-success">
                <div class="window-content">
                    <i class="success-icon"></i>
                    <p class="success-tips">{{ $setI18n('lang_comeinWallet_success_tip','成功创建钱包！') }}</p>
                    <div class="common-btn enter-wallet" @click="isShowSuccessCreateWallet = false">{{ $setI18n('lang_comeinWallet_ok','确定') }}</div>
                </div>
            </div>
            <div class="popUp-window-mesk" @click="handleClickCloseWindow"></div>
        </div>

        <!-- 下载KeyStore文件 -->
        <div class="popUp-window" v-if="isShowDownLoadJson == true" :style="isShowDownLoadJson == true ? 'display:block':''">
            <div class="window-wrapper download-keystore-file">
                <div class="window-content">
                    <div class="attetion-container">
                        <div class="attention-item">
                            <i class="no-lose-icon"></i>
                            <p class="title">{{ $setI18n('lang_comeinWallet_donot','不要丢失') }}</p>
                            <div class="description">
                                {{ $setI18n('lang_comeinWallet_donot_tips','请注意，如果您丢失了文件，将不能恢复钱包') }}
                            </div>
                        </div>
                        <div class="attention-item">
                            <i class="no-share-icon"></i>
                            <p class="title">{{ $setI18n('lang_comeinWallet_donot_share','不要分享') }}</p>
                            <div class="description">
                                {{ $setI18n('lang_comeinWallet_tips_3','如果你在欺诈网站使用文件，您的资金将会被偷走') }}
                            </div>
                        </div>
                        <div class="attention-item">
                            <i class="no-copy-icon"></i>
                            <p class="title">{{ $setI18n('lang_comeinWallet_backups','做好备份') }}</p>
                            <div class="description">
                                {{ $setI18n('lang_comeinWallet_tips_4','确保文件安全，也许有一天它会价值千万美金') }}
                            </div>
                        </div>
                    </div>
                    <div class="common-btn download-btn" @click="createWalletFunc">{{ $setI18n('lang_comeinWallet_downloadKs','下载KeyStore文件') }}</div>
                    <div class="warning">{{ $setI18n('lang_comeinWallet_tips_5','如果已经拥有钱包，请进入钱包') }}</div>
                </div>
            </div>

            <div class="popUp-window-mesk" @click="handleClickCloseWindow"></div>
        </div>

        <!-- new address -->
        <div class="popUp-window" v-if="isShowPrivateKeyWindow == true" :style="isShowPrivateKeyWindow == true ? 'display:block':''">

            <div class="window-wrapper success-deal create-wallet-success">
                <div class="window-content">
                    <i class="success-icon"></i>
                    <p class="success-tips">{{ address }}</p>
                    <p class="success-tips">{{ privateKey }}</p>
                    <div class="common-btn enter-wallet" @click="createWalletFunc">{{ $setI18n('lang_comeinWallet_downloadKs','下载KeyStore文件') }}</div>
                </div>
            </div>
            <div class="popUp-window-mesk" @click="handleClickCloseWindow"></div>

        </div>

    </div>

</template>

<script lang='ts'>
    declare let Wallet;
    declare let AES256;
    declare let Hashes;


import { Vue, Component, Prop, Watch } from "vue-property-decorator";

import { mapGetters, mapActions } from "vuex";

import { Buffer } from 'buffer';

import { Password } from '../../lib/password';

import { readInputFile } from '../../lib/utils';

import {Key} from 'smartxjs';

import { exec,exec2,geturl} from '../../lib/api';

import Utils from '@/utils/index';

import {
    getKey,
    createNewWallet,
    WalletJson_V2_0_0,
    WalletState,
    validateWallet,
    GetWalletJson_V1_0_0,
    validatePassword,
    GlobalLoadedWallet,
} from "../../model/wallet";

/** 剪切板插件 */
import VueClipboard from 'vue-clipboard2';

import QRCode from "qrcodejs2";

/** 加载图片 */
import blackLogoPng      from '@/assets/images/public/logo.png';
import LogoPng           from '@/assets/images/public/black-logo.png';
import whiteLogoPng      from '@/assets/images/public/white-logo.png';
import userDefaultPicPng from '@/assets/images/public/user.svg';
import smartxLogoPng     from '@/assets/images/public/smartx-logo.png';
import erweimaPicPng     from '@/assets/images/public/erweima-pic.png';
import {Hash} from 'smartxjs';
import BigNumber from 'bignumber.js'

Vue.use(VueClipboard);

 interface TransferNonce{
    nonce: string;
    timestamp: string;
    random: string;
 }

@Component({
    methods:{
        ...mapActions([
            'getAccountTransactionsRequestAction', 
            'getLatestBlockHeightRequestAction',
            'getAccountTransactionsCountAction'
        ])
    }
})
export default class wallet_toV101 extends Vue { 

   /** 图片 */
   private getBlackLogoPng:any      = blackLogoPng;
   private getLogoImage:any         = LogoPng;
   private getWhiteLogoPng:any      = whiteLogoPng;
   private getUserDefaultPicPng:any = userDefaultPicPng;
   private getSmartxLogoPng:any     = smartxLogoPng;
   private getErWeimaPicPng:any     = erweimaPicPng

   /** 判断是否登录 */
   private isLogin:Boolean  = false;

   /** 是否正在加载钱包; */
   private isLoadWallet:Boolean  = false;

   /** 是否正在创建钱包; */
   private isCreateWallet:Boolean = false;

   /** 是否显示download弹窗;  */
   private isShowDownLoadJson:Boolean = false;

   /** 是否显示创建钱包成功的弹窗; */
   private isShowSuccessCreateWallet:Boolean = false;

   /** 是否显示钱包上传弹窗 */
   private isShowUpLoadWallet:Boolean = false;

   /** 是否弹出输入密码加载钱包 */
   private isInputPwdWallet:Boolean = false;

   /** 是否显示发送交易窗口 */
   private isShowSendMoney:Boolean = false;

   /** 是否显示发送成功弹窗 */
   private isSendMoneySuccess:Boolean = false;

   /** 是否显示签名窗口 */
   private isShowPrivateKeyWindow:Boolean = false;

   /** 是否显示二维码 */
   private isShowQrcode:Boolean = false;

   /** 存储file对象 */
   private myFile:any     = null;

   /** 密码 */
   private pwd:string     = '';

   /** 确认密码 */
   private pwd2:string    = '';

   /** 密码 */
    private pwd3: string = '';

    private wallet: any = null;

   /**  */
   private privKey:string = '';

   /** pwd难度文字 */
   private pwdDifficultyText = this['$setI18n']('lang_common',"普通");

   private address:string = '';
 
   private from:string = '';

   private to:string   = '';

   private amount:number = 0;

   /** 转账金额 */
   private moneyNum:any  = 0;

   private key:any;

   private mySign:String  = '';

   private clearInterval:any;

   private exchangeRateRatio: any = 10000;

   /** 私密key */
   private privateKey:string = '';
   /** 当前转账hash */
   private transferHashList:Array<any> = [];
   /** 当前转账msg */
   private transfermsg:Array<any> = [];
   /** 交易列表 */
   private accountTransactionsList:Array<any> = [];

   /** 交易笔数 */
   private accountTransactionsCount:Number = 0;

   /** 是否显示交易列表 */
   private isShowMoneyList:Boolean = false;

   /** 是否显示头部的导航 */
   private isShowMenu:Boolean = false;
   private isShowMenu2:Boolean = false;
   private isShowUserMenu:Boolean = false;
   private timestamp: any = 0;

   /** 监听pwd变化 */
   @Watch('pwd',{ immediate: true, deep: true })
      onChangeForPwd(_new:string, _old:string){

        if(_new != undefined){

            /** 判断是否输入了中文，如果带有中文则删除 */
            if(/.*[\u4e00-\u9fa5]+.*$/g.test(_new)){
                 let reg = /[\u4e00-\u9fa5]/g;
                 this.pwd.replace(reg, "");
            }

            /** 去除前后空格 */
            this.pwd = this.pwd.replace(/(^\s*)|(\s*$)/g, "");
        }
   }

   /** 监听pwd变化 */
   @Watch('pwd2',{ immediate: true, deep: true })
      onChangeForPwd2(_new:string, _old:string){

        if(_new != undefined){

            /** 判断是否输入了中文，如果带有中文则删除 */
            if(/.*[\u4e00-\u9fa5]+.*$/g.test(_new)){
                 let reg = /[\u4e00-\u9fa5]/g;   
                 this.pwd.replace(reg, "");
            }

            /** 去除前后空格 */
            this.pwd2 = this.pwd2.replace(/(^\s*)|(\s*$)/g, "");

        }
   }

   /** 监听pwd变化 */
   @Watch('pwd3',{ immediate: true, deep: true })
      onChangeForPwd3(_new:string, _old:string){

        if(_new != undefined){

            /** 判断是否输入了中文，如果带有中文则删除 */
            if(/.*[\u4e00-\u9fa5]+.*$/g.test(_new)){
                 let reg = /[\u4e00-\u9fa5]/g;
                 this.pwd3.replace(reg, "");
            }

            /** 去除前后空格 */
            this.pwd3 = this.pwd3.replace(/(^\s*)|(\s*$)/g, "");
        }
   }

   private  mounted():void {
       
       this.handleClickChangeLang(1);
   }


   private handleClickChangeMoneyList(_isShowMoneyList:Boolean):void{

         this.isShowMoneyList = _isShowMoneyList;
         
         if(document.body.clientWidth  <= 750 ){

             this.isShowUserMenu = false;
         }
   }
   

   /** 切换语言 */
   private handleClickChangeLang(_type):void { 
       
       if(_type == 0){
       
          this.$i18n['locale'] = 'zh-CN';

       }else if(_type == 1){

          this.$i18n['locale'] = 'en-US';

       }else if(_type == 2){

          this.$i18n['locale'] = 'en-ID';

       }else if(_type == 3){

          this.$i18n['locale'] = 'en-PH';

       }else if(_type == 4){

          this.$i18n['locale'] = 'ru-RU';
       }

       Utils['setSessionStorage']('lang', this.$i18n['locale']);
   }

   /** 点击创建钱包按钮 */
   private handleClickCreateWallet():void{

            this.isCreateWallet = true;
            this.isLoadWallet   = false;
   }

   /** 点击进入钱包 */
   private handleClickLoadWallet():void{

            this.isCreateWallet = false;
            this.isLoadWallet   = true;

            this.isShowUpLoadWallet = true;
   }

   /** 点击弹窗创建钱包 */
   private handleClickCreateWalletForWindow():void{
       
            if(this.pwd != this.pwd2){

                alert(this['$setI18n']('lang_comeinWallet_tips_12',"两次输入的密码不一致，请重新输入!"));

                return;
            }

            this.isShowDownLoadJson = true;
   }

   /** 关闭窗口(关闭窗口其实等于重置所有的状态) */
   private handleClickCloseWindow():void{

        /** 重置状态 */
        this.resetState();
   }

    /** 还原所有的状态 */
   private resetState():void{

        this.isCreateWallet     = false;
        this.isLoadWallet       = false;
        this.isShowDownLoadJson = false;
        this.isShowSuccessCreateWallet = false;
        this.isShowUpLoadWallet = false;
        this.isInputPwdWallet = false;
        this.isShowSendMoney = false;
        this.isSendMoneySuccess = false;
        this.isShowPrivateKeyWindow = false;
        this.isShowQrcode = false;
       
        this.pwd = '';
        this.pwd2= '';
        this.pwd3= '';

        this.moneyNum = 0;

        this.myFile = null;

        this.pwdDifficultyText = this['$setI18n']('lang_common', "普通");

        // 重置input框
        var inputFile = this.$refs.inputFile;
        inputFile["type"] = 'text';
        inputFile["value"] = '';
        inputFile["type"] = 'file';
        inputFile["name"] = 'file';

   }


   /** 判断字符串中是否包含字母 */
   private hasLetter(str:String):Boolean {
    for (let i in str) {
        var asc = str.charCodeAt(parseInt(i));
        if ((asc >= 65 && asc <= 90 || asc >= 97 && asc <= 122)) {
            return true;
        }
    }
    return false;
   }

   /** 密码强度样式 */
   private pwdStyle():string{

       if(this.pwd.length < 3){

           this.pwdDifficultyText = this['$setI18n']('lang_common',"普通");
           return '0%';

       }else if(this.pwd.length > 3 && this.hasLetter(this.pwd) == false){

           this.pwdDifficultyText = this['$setI18n']('lang_secondary',"中等");
           return '33.3%';

       }else if(this.pwd.length >= 6 && this.hasLetter(this.pwd) == true){

           this.pwdDifficultyText = this['$setI18n']('lang_highStrength',"高强");'';
           return '66.6%';
       }

       return '0%';
   }

  
   /** 下载钱包 */
   private funDownload(content, filename):void {

            /** 创建隐藏的可下载链接 */
            let eleLink = document.createElement('a');

            eleLink.download = filename;

            eleLink.style.display = 'none';

            /** 字符内容转变成blob地址 */
            let blob = new Blob([content]);

            eleLink.href = URL.createObjectURL(blob);

            /** 触发点击 */
            document.body.appendChild(eleLink);

            eleLink.click();

            /** 然后移除 */ 
            document.body.removeChild(eleLink);
    };


    
    /** 加载json文件 */
    private addFileJson(event) {
           let _inputDOM = this.$refs.inputFile;
           /** 通过DOM取文件数据 */
           let _files = _inputDOM['files'];
           if (_files.length > 1) {
              alert(this['$setI18n']('lang_comeinWallet_tips_13','一次最多只能加载一个文件'));
              return;
           }
           /** 存储这个file对象; */
           this.myFile = _files[0];
           /** 重置状态 */
           //this.resetState();

           this.isShowUpLoadWallet = false;
           /** 输入密码弹窗; */
           this.isInputPwdWallet = true;
    }
    
       
    private inputFileById(id: string): Promise<string> {
          
            return readInputFile(document.getElementById(id) as HTMLInputElement);
    }


    private privateKeysOfTextarea(): string[] {

            if(this.privKey == null){

                console.log('private key input is null')
                return [];
            }

            return this.privKey == '' ? this.privKey.split(/\s/).map((e) => e.trim()).filter((e) => e) : []
    }

    // 创建钱包
    private createWalletFunc ():any {

        (async()=>{
            if (this.wallet != null) {
                const password = new Password(this.pwd3);

                //赋值给全局的wallet
                const walletState = { wallet: this.wallet, password };
                GlobalLoadedWallet.setWalletState(walletState);

                //TODO: 跳转到下载链接页面walletDownload，让用户下载smartx-wallet.json

                this.funDownload(JSON.stringify(this.wallet), 'smartx-walletV2.json');

                /** 重置所有状态 */
                this.resetState();

                /** 弹出成功创建窗口 */
                this.isShowSuccessCreateWallet = true;

                return this.wallet;
            }
         })();    
    }

    /** 读取钱包 */ 
    private loadWalletFromFile() :any {

            console.log('load wallet clicked ');

            this.inputFileById('load').then((file)=>{

                        (async()=>{

                            // 校验钱包文件是否合法
                            console.log("get file json " + file);

                            try{
                                //let _res: object = await exec('GET', `${Utils['judgingURLType']()}/?v=1.0.0&cmd=info`);
                                //let _network: string = _res['network'];
                                var wallet: any = null;
                                var pubKey2: any = null;

                                const password = new Password(this.pwd3);

                                //TODO:testnet这里写死了，需要请求接口获取到main
                                var wallettemp = JSON.parse(file)
                                if (wallettemp != null && wallettemp.version < 101) {

                                    const { address, pubKey, privKey, newWallet } = GetWalletJson_V1_0_0(file, password);
                                    this.address = address;
                                    pubKey2 = pubKey;
                                    wallet = newWallet;
                                }
                                else {
                                    throw new Error('Unrecognized wallet file version.');
                                }

                                // 检查用户输入的密码是否合法
                                const walletState = validatePassword(wallet,password);

                                //TODO:这个全局对象需要有一种类似于cookie的机制，用户退出web钱包后，这个对象也需要被清理
                                GlobalLoadedWallet.setWalletState(walletState);

                                console.log(`${Utils['judgingURLType']()}/?v=1.0.0&cmd=AdressReg&1=${this.address}&2=${wallet.accounts[0].address}&3=${pubKey2}`);

                                //提交地址对
                                let _res: object = await exec2('GET', `${Utils['judgingURLType']()}/v101?v=1.0.0&cmd=AdressReg&1=${this.address}&2=${wallet.accounts[0].address}&3=${pubKey2}`);

                                this.resetState();

                                this.isShowPrivateKeyWindow = true;

                                this.address = `Old: ${this.address}`;
                                this.privateKey = `New: ${wallet.accounts[0].address}`;
                                this.pwd = this.pwd2 = this.pwd3;
                                this.wallet = wallet;


                                return wallet;

                            }catch (e) {
                                alert('load wallet file failed ' + e);
                                console.log('load wallet file failed ' + e);
                                throw e;
                    }

                })();
            });
            return null;
    }


}

</script>

<style lang='scss'>
@import 'wallet_toV101';
</style>
